import React, { useRef, useState } from 'react';
import { Button, message, Space, Modal, Form, Input, Select, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import * as adminCustomerController from '@/services/backend/adminCustomerController';
import dayjs from 'dayjs';

const { confirm } = Modal;

const CustomerManage: React.FC = () => {
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState(false);
  const [currentCustomer, setCurrentCustomer] = useState<any>(null);
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();

  // 创建客户
  const handleCreate = async (values: any) => {
    setLoading(true);
    try {
      const response = await adminCustomerController.createCustomer({
        userName: values.userName,
        pid: values.pid,
        telephone: values.telephone,
        address: values.address,
      });
      
      if (response.code === 1) {
        message.success('客户创建成功！');
        setCreateModalVisible(false);
        form.resetFields();
        actionRef.current?.reload();
      } else {
        message.error(response.msg || '创建失败');
      }
    } catch (error) {
      console.error('创建客户失败:', error);
      message.error('创建失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 编辑客户
  const handleEdit = async (values: any) => {
    setLoading(true);
    try {
      const response = await adminCustomerController.updateCustomer({
        userId: currentCustomer.userId,
        userName: values.userName,
        telephone: values.telephone,
        address: values.address,
      });
      
      if (response.code === 1) {
        message.success('客户信息更新成功！');
        setEditModalVisible(false);
        editForm.resetFields();
        actionRef.current?.reload();
      } else {
        message.error(response.msg || '更新失败');
      }
    } catch (error) {
      console.error('更新客户失败:', error);
      message.error('更新失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 删除客户
  const handleDelete = async (userId: number) => {
    try {
      const response = await adminCustomerController.deleteCustomer(userId);
      message.success('客户删除成功！');
      actionRef.current?.reload();
    } catch (error: any) {
      console.error('删除客户失败:', error);
      // 显示具体的错误信息
      const errorMessage = error.message || '删除失败，请重试';
      message.error(errorMessage);
    }
  };

  // 打开编辑模态框
  const showEditModal = (record: any) => {
    setCurrentCustomer(record);
    editForm.setFieldsValue({
      userName: record.userName,
      telephone: record.telephone,
      address: record.address,
    });
    setEditModalVisible(true);
  };

  // 表格列定义
  const columns: ProColumns<any>[] = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      key: 'userName',
      width: 150,
    },
    {
      title: '身份证号',
      dataIndex: 'pid',
      key: 'pid',
      width: 200,
    },
    {
      title: '手机号',
      dataIndex: 'telephone',
      key: 'telephone',
      width: 150,
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
      width: 200,
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '是否管理员',
      dataIndex: 'isAdmin',
      key: 'isAdmin',
      width: 100,
      valueType: 'select',
      valueEnum: {
        true: { text: '管理员', status: 'Processing' },
        false: { text: '普通用户', status: 'Default' },
      },
      render: (_, record) => (
        <Tag color={record.isAdmin ? 'blue' : 'green'}>
          {record.isAdmin ? '管理员' : '普通用户'}
        </Tag>
      ),
    },
    {
      title: '注册时间区间',
      dataIndex: 'registerTimeRange',
      valueType: 'dateRange',
      hideInTable: true,
      search: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      valueType: 'dateTime',
      hideInSearch: true,
      render: (_, record) => record.createTime ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') : '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      search: false,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          {!record.isAdmin && (
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                confirm({
                  title: '确认删除',
                  content: `确定要删除客户 ${record.userName} 吗？`,
                  onOk: () => handleDelete(record.userId),
                });
              }}
            >
              删除
            </Button>
          )}
        </Space>
      ),
    },
  ];

  // 获取表格数据
  const fetchTableData = async (params: any) => {
    try {
      // 处理时间区间
      let startTime, endTime;
      if (params.registerTimeRange && params.registerTimeRange.length === 2) {
        startTime = params.registerTimeRange[0];
        endTime = params.registerTimeRange[1];
      }
      const response = await adminCustomerController.pageCustomers({
        ...params,
        startTime,
        endTime,
        registerTimeRange: undefined,
        current: undefined,
        pageSize: undefined,
      });

      if (response.code === 1) {
        return {
          data: response.data.records || [],
          success: true,
          total: response.data.total || 0,
        };
      } else {
        message.error(response.msg || '获取数据失败');
        return {
          data: [],
          success: false,
          total: 0,
        };
      }
    } catch (error) {
      console.error('获取客户列表失败:', error);
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  return (
    <PageContainer>
      <ProTable<any>
        headerTitle="客户管理"
        actionRef={actionRef}
        rowKey="userId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            icon={<PlusOutlined />}
            onClick={() => setCreateModalVisible(true)}
          >
            创建客户
          </Button>,
        ]}
        request={fetchTableData}
        columns={columns}
        scroll={{ x: 1200 }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 创建客户模态框 */}
      <Modal
        title="创建客户"
        open={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreate}
        >
          <Form.Item
            name="userName"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            name="pid"
            label="身份证号"
            rules={[
              { required: true, message: '请输入身份证号' },
              { pattern: /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/, message: '身份证号格式不正确' },
            ]}
          >
            <Input placeholder="请输入身份证号" />
          </Form.Item>

          <Form.Item
            name="telephone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="address"
            label="地址"
            rules={[{ required: true, message: '请输入地址' }]}
          >
            <Input placeholder="请输入地址" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                创建
              </Button>
              <Button onClick={() => {
                setCreateModalVisible(false);
                form.resetFields();
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑客户模态框 */}
      <Modal
        title="编辑客户"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          editForm.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={handleEdit}
        >
          <Form.Item
            name="userName"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            name="telephone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="address"
            label="地址"
            rules={[{ required: true, message: '请输入地址' }]}
          >
            <Input placeholder="请输入地址" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                更新
              </Button>
              <Button onClick={() => {
                setEditModalVisible(false);
                editForm.resetFields();
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default CustomerManage; 